package com.wtwd.device.netty;

import com.wtwd.device.netty.code.WTEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 超时时间
     */
    private static final int READ_IDLE_TIME =1200;

    private static final String WEBSOCKET_PROTOCOL = "webSocket";
    @Resource
    private BaseChannelHandler channelHandler;

    @Value("${netty.webSocket.path}")
    private String webSocketPath;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //设置管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new WebSocketServerProtocolHandler("/webSocket", WEBSOCKET_PROTOCOL, true, 65536));
        pipeline.addLast(new ReadTimeoutHandler(READ_IDLE_TIME));
        pipeline.addLast("WTEncoder",new WTEncoder());
        // 自定义的handler，处理业务逻辑
        pipeline.addLast(channelHandler);

    }
}
